<template>
  <view class="my-page">
    <!-- 顶部紫色背景图片 -->
    <image class="header-img" src="/static/images/card1.png" mode="widthFix" />

    <!-- 右上角操作按钮 -->
    <view class="top-actions">
      <text class="icon-edit" @click="goEditProfile">✎</text>
    </view>

    <!-- 白色卡片区域 -->
    <view class="profile-card">
      <image class="avatar" :src="userInfo.avatar || '/static/images/logo.png'" mode="aspectFill" />
      <view class="nickname">{{ userInfo.nickname || userInfo.username }}</view>
      <view class="stats">
        <text>
          <text class="num">{{ userInfo.stats.like_count }}</text>
          点赞
        </text>
        <text>
          <text class="num">{{ userInfo.stats.follow_count }}</text>
          关注
        </text>
        <text>
          <text class="num">{{ userInfo.stats.fan_count }}</text>
          粉丝
        </text>
      </view>
      <view class="bio">{{ userInfo.bio }}</view>
    </view>

    <!-- 标签页导航 -->
    <view class="tabs-container">
      <view class="tab-item" :class="{ active: activeTab === 'issued' }" @click="switchTab('issued')">发行</view>
      <view class="tab-item" :class="{ active: activeTab === 'collect' }" @click="switchTab('collect')">收藏</view>
      <view class="tab-item" :class="{ active: activeTab === 'trade' }" @click="switchTab('trade')">交易</view>
    </view>

    <!-- 作品列表 -->
    <view class="card-list">
      <view class="card" v-for="work in displayedWorks" :key="work.id" @click="goDetail(work.id)">
        <view class="card-status" :class="statusClass(work.status)">
          {{ statusText(work.status) }}
        </view>
        <image class="card-img" :src="work.image || work.image_url" mode="aspectFill" />
        <view class="card-title">{{ work.name }}</view>
        <view class="card-bottom">
          <text class="price">¥{{ work.price }}</text>
          <text class="likes">
            <text class="icon">♡</text>
            {{ work.like_count || 0 }}
          </text>
        </view>
      </view>
      <view v-if="!displayedWorks.length" class="empty-box">
        <image src="/static/images/empty.png" class="empty-img" mode="aspectFit" />
        <text class="empty-text">暂无数据</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { http } from '@/pages/utils/Http';
import type { UserInfoResponse, UserInfo } from '@/pages/utils/request';
import { onShow } from '@dcloudio/uni-app';

// 用户信息
const userInfo = ref<UserInfo>({
  id: 0,
  username: '',
  avatar: '/static/images/logo.png',
  nickname: '用户',
  bio: '',
  stats: {
    like_count: 0,
    follow_count: 0,
    fan_count: 0,
    work_issued: 0,
    work_collect: 0,
  },
});

// 作品列表
const issuedList = ref<any[]>([]);
const collectList = ref<any[]>([]);
const tradeList = ref<any[]>([]);

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const storedUserId = uni.getStorageSync('userId');
    const storedUsername = uni.getStorageSync('username');

    if (!storedUserId && !storedUsername) {
      uni.showToast({ title: '用户未登录', icon: 'none' });
      return;
    }

    const params: any = storedUserId ? { userId: storedUserId } : { username: storedUsername };

    const res = await http.get<UserInfoResponse>('/api/user/profile', params);
    if (res.code === 200) {
      userInfo.value = res.data;
    }
  } catch (err) {
    uni.showToast({ title: '获取用户信息失败', icon: 'none' });
  }
};

// 获取作品列表
const fetchWorks = async () => {
  try {
    const storedUserId = uni.getStorageSync('userId');
    if (!storedUserId) return;
    const res = await http.get<any>('/api/works', { userId: storedUserId });
    if (res.code === 200 && Array.isArray(res.data)) {
      // 假设后端每条作品含 status 字段: review/issued/done/hot 等
      issuedList.value = res.data.filter((w: any) => w.category === 'issued');
      collectList.value = res.data.filter((w: any) => w.category === 'collect');
      tradeList.value = res.data.filter((w: any) => w.category === 'trade');
    }
  } catch (e) {
    console.error(e);
  }
};

// 首次加载
onMounted(() => {
  fetchUserInfo();
  fetchWorks();
});

// 当页面重新显示时（例如从创建作品页返回）自动刷新
onShow(() => {
  fetchUserInfo();
  fetchWorks();
});

// 选项卡状态管理
const activeTab = ref('issued');

const displayedWorks = computed(() => {
  switch (activeTab.value) {
    case 'issued':
      return issuedList.value;
    case 'collect':
      return collectList.value;
    case 'trade':
      return tradeList.value;
    default:
      return [];
  }
});

const switchTab = (tab: string) => {
  activeTab.value = tab;
};

const goDetail = (id: number) => {
  uni.navigateTo({ url: `/pages/Detail/Detail?id=${id}` });
};

const goEditProfile = () => {
  uni.navigateTo({ url: '/pages/EditProfile/EditProfile' });
};

const statusText = (s: string) => {
  switch (s) {
    case 'review': return '审核中';
    case 'issued': return '已发行';
    case 'done': return '已结束';
    case 'hot': return '热门';
    default: return s;
  }
};

const statusClass = (s: string) => {
  return {
    'status-review': s === 'review',
    'status-issued': s === 'issued',
    'status-done': s === 'done',
    'status-hot': s === 'hot'
  };
};
</script>

<style lang="scss">
/* 全局样式 */
.my-page {
  background: #f7f7fa;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  /* 1. 使用绝对定位，让页面脱离文档流 */
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /* 2. 让页面自身可滚动 */
  overflow-y: auto;
  box-sizing: border-box;
  padding-bottom: 24px;
  /* 保留底部安全间隙 */
}

.header-img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  display: block;
}

/* 顶部右侧按钮 */
.top-actions {
  position: absolute;
  top: 14px;
  right: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  z-index: 5;

  .icon-edit {
    font-size: 20px;
    color: #ffffff;
    opacity: 0.9;
  }
}

.profile-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(160, 160, 160, 0.08);
  margin: -48px 16px 0 16px;
  padding: 24px 0 12px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;

  .avatar {
    width: 72px;
    height: 72px;
    border-radius: 50%;
    border: 4px solid #fff;
    margin-bottom: 8px;
    margin-top: -36px;
    background: #fff;
    object-fit: cover;
  }

  .nickname {
    font-size: 22px;
    font-weight: bold;
    color: #222;
    margin-bottom: 2px;
  }


  .stats {
    display: flex;
    gap: 24px;
    font-size: 15px;
    color: #222;
    margin-bottom: 8px;

    .num {
      font-weight: bold;
      font-size: 16px;
      margin-right: 2px;
    }
  }

  .bio {
    font-size: 13px;
    color: #888;
    text-align: center;
    margin: 0 16px;
  }
}

/* 标签页导航 */
.tabs-container {
  display: flex;
  margin: 16px;
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 14px 0;
    font-size: 16px;
    color: #666;
    position: relative;

    &.active {
      color: #1976d2;
      font-weight: 600;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 3px;
        background-color: #1976d2;
        border-radius: 2px;
      }
    }
  }
}

/* 作品网格 */
.works-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 0 16px 20px;

  .work-item {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .work-image {
    width: 100%;
    height: 160px;
    display: block;
  }

  .work-info {
    padding: 12px;
  }

  .work-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 6px;
  }

  .work-price {
    font-size: 16px;
    font-weight: bold;
    color: #ff5722;
    margin-bottom: 8px;
  }

  .work-status {
    font-size: 12px;
    color: #4caf50;
    background-color: #e8f5e9;
    padding: 4px 8px;
    border-radius: 4px;
    display: inline-block;

    &.reviewing {
      background-color: #fff8e1;
      color: #ff8f00;
    }

    &.issued {
      background-color: #e8f5e9;
      color: #2e7d32;
    }

    &.rejected {
      background-color: #ffebee;
      color: #c62828;
    }
  }
}

.card-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  padding: 0 12px;
  margin-top: 8px;
  box-sizing: border-box;
}

.card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(160, 160, 160, 0.1);
  padding: 10px 6px 8px 6px;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
  box-sizing: border-box;
  min-width: 0;
}

.card-status {
  position: absolute;
  top: 12px;
  right: 12px;
  border-radius: 8px;
  font-size: 12px;
  padding: 2px 10px;
  color: #fff;
  font-weight: 500;
  z-index: 2;

  &.status-review {
    background: #6dd400;
  }

  &.status-issued {
    background: #ffb800;
  }

  &.status-done {
    background: #bbb;
  }

  &.status-hot {
    background: #ff3b30;
  }
}

.card-img {
  width: 100%;
  border-radius: 12px;
  margin-bottom: 8px;
  aspect-ratio: 1/1;
  object-fit: cover;
  background: #f5f5f5;
  height: auto;
  max-height: 120px;
}

.card-title {
  font-size: 15px;
  font-weight: bold;
  color: #222;
  margin-bottom: 4px;
  margin-top: 0;
}

.card-bottom {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #ff3b30;
  font-size: 15px;
  font-weight: bold;
}

.likes {
  color: #bbb;
  font-size: 13px;
  display: flex;
  align-items: center;

  .icon {
    font-size: 13px;
    margin-right: 2px;
  }
}

.empty-box {
  width: 100%;
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;

  .empty-img {
    width: 160rpx;
    height: 160rpx;
    margin-bottom: 20rpx;
    opacity: 0.6;
  }

  .empty-text {
    color: #999;
    font-size: 28rpx;
  }
}
</style>
